package com.goldsprite.gameframeworks.ecs.component;

import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.goldsprite.gameframeworks.utils.math.Vector2;

import java.util.LinkedHashMap;
import java.util.Map;

public class AnimatorComponent extends Component {
	public Map<String, Animation<TextureRegion>> anims = new LinkedHashMap<>();
	public Map<String, Vector2> animOriginOffsets = new LinkedHashMap<>();
	public Map<String, Vector2> animScales = new LinkedHashMap<>();

	public float stateTime;
	public String current, lastAnim;

	private boolean fixed;
	private Vector2 oldOriginOffset = new Vector2();
	private Vector2 oldScl = new Vector2();

	public void playAnim(String key){
		playAnim(key, true);
	}
	public void playAnim(String key, boolean reset){
		if (!anims.containsKey(key)) return;

		if(!key.equals(current) && reset) stateTime = 0;

		if(!key.equals(current)) {
			onAnimChange(lastAnim, current, key);
		}

		current = key;
	}

	protected void onAnimChange(String lastAnim, String current, String nextAnim) {

		this.lastAnim = current;
		//动画单独偏移
		if(fixed){
			getSpriteComponent().getOriginOffset().set(oldOriginOffset);
			getSpriteComponent().getScale().set(oldScl);
		}
		fixed = false;
		if(animOriginOffsets.containsKey(nextAnim)){
			Vector2 nextOriginOffset = animOriginOffsets.get(nextAnim);
			Vector2 nextScl = animScales.get(nextAnim);

			oldOriginOffset.set(getSpriteComponent().getOriginOffset());
			oldScl.set(getSpriteComponent().getScale());

			getSpriteComponent().getOriginOffset().set(nextOriginOffset);
			getSpriteComponent().getScale().set(nextScl);

			fixed = true;
		}
	}

	public void addAnim(String key, Animation<TextureRegion> anim){
		addAnim(key, anim, null, 0);
	}
	public void addAnim(String key, Animation<TextureRegion> anim, Vector2 originOffset, float scl){
		if(current == null) current = key;
		anims.put(key, anim);
		if (originOffset != null) {
			animOriginOffsets.put(key, originOffset);
			animScales.put(key, new Vector2().set(scl));
		}
	}

	public void step(float delta){
		try {
            // 更新动画
            if (current != null && anims.containsKey(current)) {
                TextureRegion keyFrame = getAnim(current).getKeyFrame(stateTime);
                getSpriteComponent().setRegion(keyFrame);
                stateTime += delta;
            }
		} catch (Exception e) {
			//没有动画就什么也不做
		}
	}

	public SpriteComponent getSpriteComponent(){
		return getComponent(SpriteComponent.class);
	}

	public Animation<TextureRegion> getAnim(String key) {
		return anims.get(key);
	}

	public int curAnimFrameIndex(){
		return anims.get(current).getKeyFrameIndex(stateTime);
	}

	public boolean isAnim(String key) {
		return anims.containsKey(key) && current.equals(key);
	}
	public Animation<TextureRegion> getCurrentAnim(){
		return getAnim(current);
	}
	public boolean isAnimCompleted() {
		return getAnim(current).isAnimationFinished(stateTime);
	}
}
